//
//  HMImageDownloadOperation.m
//  ImageLoader
//
//  Created by Le Ngoc Thanh on 8/23/13.
//  Copyright (c) 2013 Le Ngoc Thanh. All rights reserved.
//

#import "HMImageDownloadOperation.h"
#import "HMStoreImage.h"

@implementation HMImageDownloadOperation
- (id)init
{
    __weak typeof(self) weakSelf = self;
    weakSelf = [super init];
    if (weakSelf) {
        [weakSelf setCompletionBlock:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:_imageUrl object:_imageUrl];
            });
        }];
    }
    return weakSelf;
}
- (void)main{
    if ([self isCancelled]) {
        //NSlog(@"Cancell");
        return;
    }
    // download Image
    NSData *data = nil;
    if (![[HMStoreImage share] isDownloaded:self.imageUrl]) {
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.imageUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
        NSLog(@"%@",_imageUrl);
        NSHTTPURLResponse *res = nil;
        NSError *err;
        data = [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&err];
        
        if(!err){
            if (data && res.statusCode == 200) {
                if (self.isOverride) {
                    [[HMStoreImage share] removeFromOnlineLink:self.imageUrl];
                }
                if (self.localUrl) {
                    [[HMStoreImage share] saveData:data forOnlineUrl:self.imageUrl atLocalLink:self.localUrl];
                }else{
                    [[HMStoreImage share] saveData:data forOnlineUrl:self.imageUrl];
                }
                
                NSLog(@"success");
            }
        }else{
            NSLog(@"%@",err);
        }
    }else{
        NSLog(@"already have");
    }
    
    NSLog(@"%d",[[NSURLCache sharedURLCache] currentMemoryUsage]);
    if ([self isCancelled]) {
        return;
    }
    data = nil;
//    __block NSString *notificationKey = self.imageUrl;
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [[NSNotificationCenter defaultCenter] postNotificationName:notificationKey object:notificationKey];
//    });
}
- (BOOL)isEqual:(id)object{
    if ([object isKindOfClass:[HMImageDownloadOperation class]]) {
        if ([((HMImageDownloadOperation *)object).imageUrl isEqual:self.imageUrl]) {
            return YES;
        }
    }
    return NO;
}

+ (HMImageDownloadOperation *)operationWithImageLink:(NSString *)imageString isOverride:(BOOL)override{
    HMImageDownloadOperation *oper = [[HMImageDownloadOperation alloc] init];
    oper.imageUrl = imageString;
    oper.isOverride = override;
    oper.localUrl = nil;
    return oper;
}
+ (HMImageDownloadOperation *)operationWithImageLink:(NSString *)imageString localLink:(NSString *)local isOverride:(BOOL)override{
    HMImageDownloadOperation *oper = [[HMImageDownloadOperation alloc] init];
    oper.imageUrl = imageString;
    oper.isOverride = override;
    oper.localUrl = local;
    return oper;
}
@end